import {Modal, Toast} from "antd-mobile";
import axios from "axios";
import {GetCookie} from '../redux/LogicalOperation'

const instance = axios.create({
    baseURL: 'http://localhost:3000',
    timeout: 5000 // request timeout
})

// 是否正在刷新token
let isRefreshing = false;
// token 过期时的请求队列
let requestQueue = [];

//token获取失败处理
const LoginAgain = () => {
    Modal.warning({
        content: "登录错误，请重新登录！",
        centered: true,
        okText: "确认",
        onOk() {
            // 弹出登录弹框
        },
    });
};

// 请求拦截
instance.interceptors.request.use((config) => {
    // 可以记录请求开始的时间 响应里面上报 接口耗时
    config.REQUEST_ID = Date.now();
    // 请求REQUEST_ID url timestamp 上报
    try {
        // 设置请求头的token参数
        config.headers.authentication = GetCookie('token') || "";
    } catch (error) {
        console.log(error.message);
    }
    return config;
});


// 响应拦截
instance.interceptors.response.use(config => {
        if (config.data.status === 401) {
            // token失效
            isRefreshing = true;
            const {config} = config;
            if (isRefreshing) {
                return new Promise((resolve) => {
                    requestQueue.push((token) => {
                        config.headers.token = token;
                        resolve(instance(config));
                    });
                });
            }
        }
        return Promise.resolve(config);
    },
    (error) => {
        Toast.fail('网络错误！', 2);
        return Promise.reject(error);
    }
);


export default instance;